﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Qplus.Commands;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using Qplus.beans;
using Qplus.enums;

namespace Qplus.UI
{
    public partial class FriendControl : UserControl
    {
        int type;
        int userID;
        string userName;
        string userLevel;
        int headType;
        string headValue;

        friendCtrlTypeEnum ctrlType;
        DateTime birthday = DateTime.Parse("2000/01/01");
        E_SEX userSex = E_SEX.SEX_NOTSET;
        public FriendControl()
        {
            InitializeComponent();
        }

        public int Type
        {
            get { return type; }
            set { type = value; }
        }
        public int UserID
        {
            set {
                userID = value;
                UserName = "ID:" + UserID.ToString();
            }
            get { return userID; }
        }
        public string UserName
        {
            set { userName = value; nickNameTxt.Text = value; }
            get { return userName; }
        }
        public string UserLevel
        {
            get { return userLevel; }
            set { userLevel = value; }
        }
        public int HeadType
        {
            get { return headType; }
            set { headType = value; }
        }
        public string HeadValue
        {
            get { return headValue; }
            set { headValue = value; }
        }

        public friendCtrlTypeEnum CtrlType
        {
            set
            {
                ctrlType = value;
                if (ctrlType == friendCtrlTypeEnum.search)
                {
                    nickNameTxt.Text = "好友搜索";
                    ImageBrush imgBrh = new ImageBrush()
                    {
                        ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/icon_search_friends_item.png", UriKind.RelativeOrAbsolute)),
                        Stretch = Stretch.None,
                    };
                    frndBtnEx.Background = imgBrh;
                    frndBtnEx.PressedBackground = imgBrh;
                }
            }
            get { return ctrlType; }
        }
        public E_SEX Sex
        {
            set { userSex = value; }
            get { return userSex; }
        }
        public DateTime Birthday
        {
            set { birthday = value; }
            get { return birthday; }
        }
        public SolidColorBrush CtrlBackGround
        {
            set { ContentGrid.Background = value; }
        }

        public ImageBrush BtnExBackGround
        {
            set 
            {
                frndBtnEx.Background = value;
                frndBtnEx.PressedBackground = value;
            }
        }

        public Visibility delFrndBtnExShow
        {
            set { delFrndBtnEx.Visibility = value; }
        }

        #region EVENT
        public void frndBtnEx_Click(object sender, RoutedEventArgs e)
        {
            switch (CtrlType)
            {
                case friendCtrlTypeEnum.search:
                    {
                        GetChatListCommand command = new GetChatListCommand(QplusT.Instance.getUser().userID.ToString(), System.Text.Encoding.UTF8.GetString(QplusT.Instance.getUser().key, 0, QplusT.Instance.getUser().key.Length));
                        command.MessageReceivedFromHttpServer+=new EventHandler<Infrastructure.MessageReceivedFromServer>(command_MessageReceivedFromHttpServer);
                        command.execute(QplusT.Instance.getUser().url);
                        //GetUserListCommand command = new GetUserListCommand(QplusT.Instance.getUser().userID, QplusT.Instance.getUser().key);
                        //command.MessageReceivedFromHttpServer += new EventHandler<Infrastructure.MessageReceivedFromServer>(command_MessageReceivedFromHttpServer);
                        //command.set(2);
                        //command.execute(QplusT.Instance.getUser().url);
                        //(App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/UI/SearchFriends.xaml", UriKind.Relative));
                        //gotoSearchPage(sender,e);
                        break;
                    }
                case friendCtrlTypeEnum.friend:
                        {
                            //(App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/UI/ChatFriend.xaml?nickName=" + UserName, UriKind.Relative));
                            gotoChatPage(sender, e);
                            break;
                        }
                case friendCtrlTypeEnum.stranger:
                        {
                            //System.Windows.Navigation.NavigationService service = ((Application.Current as App).RootFrame.Content as Page).NavigationService;
                            //PopupContainer pc = new PopupContainer((Application.Current as App).RootFrame.Content as PhoneApplicationPage);// ((Application.Current.RootVisual as PhoneApplicationFrame).GetVisualDescendants().OfType<PhoneApplicationPage>().FirstOrDefault());
                            //PopupUserInfo popupUserInfo = new PopupUserInfo() { userName = nickNameTxt.Text, userAge = (DateTime.Now.Year - Birthday.Year).ToString(), userSex = Sex };
                            //pc.Show(popupUserInfo);
                            popupStranger(sender, e);
                            break;
                        }
                case friendCtrlTypeEnum.notype:
                default:
                        {
                            //Type Wrong
                            break;
                        }
            }
        }

        void command_MessageReceivedFromHttpServer(object sender, Infrastructure.MessageReceivedFromServer e)
        {
            //throw new NotImplementedException();
            JArray ja = null;
            try
            {
                SearchData.Instance.ChatList = JArray.Parse(e.strMessage);
                
            }
            catch(Exception ee)
            {
                Debug.WriteLine("Jason string parse wrong:Can not get ChatList." + ee.Message);
            }
            gotoSearchPage();
        }
        public void gotoSearchPage()//(object sender, RoutedEventArgs e)
        {
            (App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/UI/SearchFriends.xaml", UriKind.Relative));
            #region
            //int time=0;
            //l2cInfo local=new l2cInfo();
            //DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(100) };
            //DelayedTimer.Tick += (s, e0) =>
            //{
            //    //perform action
            //    time++;
            //    System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<l2cInfo>("l2cInfo", out local);
            //    GetUserListCommand command_GetUserList = new GetUserListCommand(local.UserID, local.Key);
            //    command_GetUserList.set(1);
            //    command_GetUserList.execute(local.UpgradeURL);
            //    System.Threading.Thread.Sleep(100);
            //    if(null!=local || time == 10)
            //        DelayedTimer.Stop();
            //};
            //DelayedTimer.Start();
            //System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);// (100);
            //l2cInfo local;
            //System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue<l2cInfo>("l2cInfo", out local);
            //GetUserListCommand command_GetUserList = new GetUserListCommand(local.UserID, local.Key);
            //command_GetUserList.set(1);
            //command_GetUserList.execute(local.UpgradeURL);
            //GetUserCommand command = new GetUserCommand(local.UserID, local.Key);
            //command.set(1);
            //command.execute(local.UpgradeURL);
            //DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(20) };
            //DelayedTimer.Tick += (s, e0) =>
            //{
            //    //perform action
            //    DelayedTimer.Stop();
            //    (App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/UI/SearchFriends.xaml", UriKind.Relative));
            //};
            //DelayedTimer.Start();
            #endregion
        }
        public void gotoChatPage(object sender, RoutedEventArgs e)
        {
            protocol.C2U_REQ_SESSION_BEGIN command = new protocol.C2U_REQ_SESSION_BEGIN();
            command.startOneChat(123, UserID);
            (App.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/UI/ChatFriend.xaml?nickName=" + UserName, UriKind.Relative));
        }
        public void popupStranger(object sender, RoutedEventArgs e)
        {
            //System.Windows.Navigation.NavigationService service = ((Application.Current as App).RootFrame.Content as Page).NavigationService;
            PopupContainer pc = new PopupContainer((Application.Current as App).RootFrame.Content as PhoneApplicationPage);// ((Application.Current.RootVisual as PhoneApplicationFrame).GetVisualDescendants().OfType<PhoneApplicationPage>().FirstOrDefault());
            PopupUserInfo popupUserInfo = new PopupUserInfo() {userID=this.UserID, userName = nickNameTxt.Text, userAge = (DateTime.Now.Year - Birthday.Year).ToString(), userSex = Sex };
            pc.Show(popupUserInfo);
        }
        private void delFrndBtnEx_Click(object sender, RoutedEventArgs e)
        {
            if (CtrlType == friendCtrlTypeEnum.friend)
            {
                ButtonEx tmp = sender as ButtonEx;
                Grid tmpGrid = tmp.Parent as Grid;
                FriendControl tmpFriendControl = tmpGrid.Parent as FriendControl;
                WrapPanel parentWP = tmpFriendControl.Parent as WrapPanel;
                parentWP.Children.RemoveAt(parentWP.Children.IndexOf(tmpFriendControl));
            }
        }
        private void UserControl_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //if (ctrlType == friendCtrlTypeEnum.friend)
            //{
            //    delFrndBtnEx.Visibility = System.Windows.Visibility.Visible;
            //    frndBtnEx.Click -= frndBtnEx_Click;
            //    DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
            //    DelayedTimer.Tick += (s, e0) =>
            //    {
            //        //perform action
            //        DelayedTimer.Stop();
            //        frndBtnEx.Click += frndBtnEx_Click;
            //    };
            //    DelayedTimer.Start();
            //}
        }

        private void UserControl_LostFocus(object sender, RoutedEventArgs e)
        {
            //if (delFrndBtnEx.IsFocused == false)
            {
                //delFrndBtnEx.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void frndBtnEx_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MessageBoxButton msgBtn = MessageBoxButton.OKCancel;
            MessageBoxResult result = MessageBox.Show("确实要删除好友嘛？", "", msgBtn);
            if (ctrlType == friendCtrlTypeEnum.friend)
            {
                frndBtnEx.Click -= frndBtnEx_Click;
                if (result == MessageBoxResult.OK)
                {
                    ButtonEx tmp = sender as ButtonEx;
                    Grid tmpGrid = tmp.Parent as Grid;
                    FriendControl tmpFriendControl = tmpGrid.Parent as FriendControl;
                    WrapPanel parentWP = tmpFriendControl.Parent as WrapPanel;
                    parentWP.Children.RemoveAt(parentWP.Children.IndexOf(tmpFriendControl));
                }
                else if(result == MessageBoxResult.Cancel)
                {
                    DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
                    DelayedTimer.Tick += (s, e0) =>
                    {
                        //perform action
                        DelayedTimer.Stop();
                        frndBtnEx.Click += frndBtnEx_Click;
                    };
                    DelayedTimer.Start();
                }
            }
            #region
            //if (ctrlType == friendCtrlTypeEnum.friend)
            //{
            //    delFrndBtnEx.Visibility = System.Windows.Visibility.Visible;
            //    frndBtnEx.Click -= frndBtnEx_Click;
            //    DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
            //    DelayedTimer.Tick += (s, e0) =>
            //    {
            //        //perform action
            //        DelayedTimer.Stop();
            //        frndBtnEx.Click += frndBtnEx_Click;
            //    };
            //    DelayedTimer.Start();

            //    DispatcherTimer DelTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(5) };
            //    DelTimer.Tick += (s, e0) =>
            //    {
            //        //perform action
            //        DelTimer.Stop();
            //        this.delFrndBtnEx.Visibility = System.Windows.Visibility.Collapsed;
            //    };
            //    DelTimer.Start();
            //}
            #endregion
        }
        #endregion
    }
    //public class FriendControl : System.Collections.ObjectModel.ObservableCollection<FriendControl>
    //{
    //    public FriendControl(int i)
    //    {
    //        Add(new FriendControl());
    //        Add(new FriendControl());
    //        Add(new FriendControl());
    //        Add(new FriendControl());
    //    }

    //    private void Add(FriendControl friendControl)
    //    {
    //        throw new NotImplementedException();
    //    }

    //}

}
